package com.netty.cn.rpc.string;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

import com.netty.cn.rpc.string.client.StringClientHandler;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * 
 * @author wangzonghui
 * @date 2021-07-19 16:36:36
 * @Description string类型netty客户端
 */
public class RpcStringClient {
	
	private  Channel channel;
	private  Bootstrap clientBootstap;
	
	private  String host="localhost";
	private  int port=9090;

    public static void main(String[] args) {
    	RpcStringClient rpcStringClient=new RpcStringClient();
    	rpcStringClient.startClient(rpcStringClient);
    }

    public  void startClient(RpcStringClient rpcStringClient){
        //1.定义服务类
         clientBootstap = new Bootstrap();

        //2.定义执行线程组
        EventLoopGroup worker = new NioEventLoopGroup();

        //3.设置线程池
        clientBootstap.group(worker);

        //4.设置通道
        clientBootstap.channel(NioSocketChannel.class);

        //5.添加Handler
        clientBootstap.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                System.out.println("client channel init!");
                ChannelPipeline pipeline = channel.pipeline();
                pipeline.addLast("StringDecoder",new StringDecoder());
                pipeline.addLast("StringEncoder",new StringEncoder());
                pipeline.addLast("ClientHandler",new StringClientHandler(rpcStringClient));
            }
        });

        //6.建立连接
        ChannelFuture channelFuture = clientBootstap.connect(host,port);
        try {
            //7.测试输入
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            while(true){
                System.out.println("请输入：");
                String msg = bufferedReader.readLine();
                channelFuture.channel().writeAndFlush(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //8.关闭连接
            worker.shutdownGracefully();
        }
    }
    
    public  void doConnect() {
    	if (channel != null && channel.isActive()) {
			return;
		}
    	
		ChannelFuture future = clientBootstap.connect(host,port);

		future.addListener(new ChannelFutureListener() {
			public void operationComplete(ChannelFuture futureListener) throws Exception {
				if (futureListener.isSuccess()) {
					channel = futureListener.channel();
					System.out.println("连接服务端成功!");
				} else {
					System.out.println("连接失败 ，10s 后尝试连接 "+host+":"+port);

					futureListener.channel().eventLoop().schedule(new Runnable() {
						@Override
						public void run() {
							doConnect();
						}
					}, 10, TimeUnit.SECONDS);
				}
			}
		});
    	
    }
}
